<template>
  <!-- 订单列表 -->
  <scroll-view scroll-y class="orders" refresher-enabled @refresherrefresh="onRefresherrefresh">
    <view class="card" v-for="item in orderList" :key="item.registration?.patientId">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ item.careHistory?.chId }}</text>
        <!-- 订单状态文字 -->
        <view>
          <text v-if="queryParams.orderState == 0">待付款</text>
          <text v-if="queryParams.orderState == 1">已支付</text>
          <text v-if="queryParams.orderState == 2">已退费</text>
          <text v-if="queryParams.orderState == 3">已完成</text>
          <text class="icon-delete"></text>
        </view>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <view class="orderItem">
        <view class="left">
          <image :src="item?.user?.picture"></image>
        </view>
        <view class="right">
          <navigator
              v-for="(order, index) in item.careOrders"
              hover-class="none"
              :url="`/pagesOrder/details/details?id=${order.chId}&orderState=${orderState}`"
              :key="order.coId"
              @tap="currentChId = order.chId"
          >
            <view class="text">
              <text style="color: #27ba9b">【{{ order.coType == 0 ? '药用' : '检测' }}处方】</text>
              <text>【{{ index + 1 }}】</text>
              <text>【处方总额】￥{{ order.allAmount }}</text>
            </view>
          </navigator>
        </view>
      </view>

      <view class="introduction">
        <view>医生名称：{{ item?.user?.userName }}</view>
        <view>科室：{{ item?.dept?.deptName }}</view>
        <view>订单类型：{{ item?.registration?.schedulingType == 1 ? '门诊' : '急诊' }}</view>
        <view
          >预约时间：
          {{ item?.registration?.visitDate }}
          {{
            item?.registration?.subsectionType == 1
              ? '上午'
              : item?.registration?.subsectionType == 2
                ? '下午'
                : '晚上'
          }}
        </view>
      </view>

      <!-- 支付信息 -->
      <view class="payment" v-if="queryParams.orderState != 1">
        <text class="quantity"
          >共{{ calculateTotalsByChId(item.careHistory?.chId).totalNum }}件商品</text
        >
        <text v-show="queryParams.orderState == 4 || queryParams.orderState == 0">应付金额</text>
        <text v-show="queryParams.orderState == 2">已退金额</text>
        <text class="amount">
          <text class="symbol">¥</text>
          {{ calculateTotalsByChId(item.careHistory?.chId).totalAmount }}
        </text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="queryParams.orderState == 0">
          <navigator
            :url="`/pagesOrder/details/details?id=${item.careHistory?.chId}&orderState=${0}`"
            class="button primary"
          >
            去支付
          </navigator>
        </template>
        <template v-else-if="queryParams.orderState == 1">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/back/backFee?id=${item.careHistory?.chId}&orderState=${6}`"
            hover-class="none"
          >
            点击退款
          </navigator>
        </template>
        <template v-else-if="queryParams.orderState == 3">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/score/score?chId=${item.careHistory?.chId}`"
            hover-class="none"
          >
            去评价
          </navigator>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ true ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { OrderListParams } from '@/types/order'
import { getMemberOrderAPI } from '@/services/order'
import type { OrderListDto } from '@/types/orderList'
import { onLoad } from '@dcloudio/uni-app'
import { backAPI } from '@/services/pay'
import type { LoginResult } from '@/types/member'
import { useMemberStore } from '@/stores'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义 props
const props = defineProps<{
  orderState: string
}>()

const memberStore = useMemberStore()
const memberInfo = memberStore.profile as LoginResult
const phonePatient = memberInfo.phone

// 请求参数
const queryParams: Required<OrderListParams> = {
  page: 1,
  pageSize: 5,
  phone: phonePatient,
  orderState: props.orderState,
}

// 获取订单列表
const orderList = ref<OrderListDto[]>([])

// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)

const getMemberOrderData = async () => {
  isLoading.value = true

  try {
    const res = await getMemberOrderAPI(queryParams)

    if (res.code === 200 && res.data) {
      orderList.value = res.data as OrderListDto[]
      console.log('数据5254254', orderList.value)

      // 初始化 currentChId
      if (orderList.value.length > 0) {
        currentChId.value = orderList.value[0].careHistory?.chId || null
      }
    } else {
      console.error('请求失败或数据格式不正确', res)
    }
  } catch (error) {
    console.error('请求时发生错误', error)
  } finally {
    isLoading.value = false
  }
}

console.log('数据' + orderList.value)
onLoad(() => {
  getMemberOrderData()
})

// 订单支付
const onOrderPay = async (id: string) => {
  if (import.meta.env.DEV) {
    // 开发环境模拟支付
    // await getPayMockAPI({ orderId: id })
  } else {
    // #ifdef MP-WEIXIN
    // 正式环境支付：1.获取支付订单信息，2.调用微信支付API
    // const res = await getPayWxPayMiniPayAPI({ orderId: id })
    // await wx.requestPayment(res.result)
    // 注意：因小程序上线后被恶意投诉：理由为支付 0.01 元后不发货，现调整为模拟支付
    // await getPayMockAPI({ orderId: id })
    // #endif
  }
}

// 当前选中的 chId
const currentChId = ref<string | null>(null)

// 计算每个 chId 的总数量和总金额
const calculateTotalsByChId = (chId: string) => {
  const filteredOrders = orderList.value.filter((item) => item.careHistory?.chId === chId)
  const totalNum = filteredOrders.reduce(
    (sum, item) =>
      sum +
      (item.careOrderItems?.reduce((itemSum, orderItem) => itemSum + (orderItem.num || 0), 0) || 0),
    0,
  )

  const totalAmount = filteredOrders.reduce(
    (sum, item) =>
      sum +
      (item.careOrderItems?.reduce((itemSum, orderItem) => itemSum + (orderItem.amount || 0), 0) ||
        0),
    0,
  )

  return { totalNum, totalAmount }
}

// 刷新数据
const onRefresherrefresh = async () => {
  queryParams.page = 1
  orderList.value = []
  await getMemberOrderData()
}

// 返回上一页
const back = (chId: string | null) => {
  // your implementation
}
</script>

<style lang="scss" scoped>
// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .orderItem {
    display: flex;
    margin: 20rpx 0;

    .left {
      flex: 3;

      image {
        width: 125rpx;
        height: 125rpx;
      }
    }

    .right {
      flex: 9;

      .text {
        margin: 20rpx 0;
        font-size: 24rpx;
      }
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;

      image {
        width: 170rpx;
        height: 170rpx;
        border-radius: 50%;
      }
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
      border-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
